<!-- 商户报表 -->
<template>
  <SearchTable :query="data.query" :list="data.list" :total="data.total" :showPanel="false" :showExport="true"
    @changeSize="changeSize" @download="getSearchList('export')" @changePage="changePage" @search="getSearchList"
    @reset="onHideDetails(true)" @changeTh="data.dialogVisible = true">
    <template #form>
      <el-form-item label="地区：" v-if="!indexStore.is_general_agent">
        <el-select class="formItem500" v-model="data.query.area_s" filterable multiple placeholder="请选择">
          <el-option v-for="(item, index) in COUNTRY" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="货币：" v-if="!indexStore.is_general_agent">
        <el-select class="formItem500" v-model="data.query.currency_ids" filterable multiple placeholder="请选择">
          <el-option v-for="(item, index) in data.currentList" :key="index"
            :label="item.name + ' (' + item.symbol + ')' + '-' + item.remark" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="日期时间：">
        <el-date-picker v-model="data.query.date" type="daterange" range-separator="-" start-placeholder="请选择开始时间"
          end-placeholder="请选择结束时间" value-format="YYYY-MM-DD" :disabled-date="indexStore.disabledDateTime"/>
      </el-form-item>
      <Operator ref="OperatorRef" @query="queryItem" />
    </template>
    <template #button>
      <div class="statistic flex">
        <el-button :type="data.dayIndex == 1 ? 'success' : ''" :disabled="indexStore.loading"
          @click="changeTime(1)">今日</el-button>
        <el-button :type="data.dayIndex == 2 ? 'success' : ''" :disabled="indexStore.loading"
          @click="changeTime(2)">昨日</el-button>
        <el-button :type="data.dayIndex == 3 ? 'success' : ''" :disabled="indexStore.loading"
          @click="changeTime(3)">上周</el-button>
        <el-button :type="data.dayIndex == 4 ? 'success' : ''" :disabled="indexStore.loading"
          @click="changeTime(4)">本周</el-button>
        <el-button :type="data.dayIndex == 5 ? 'success' : ''" :disabled="indexStore.loading"
          @click="changeTime(5)">本月</el-button>
        <el-button :type="data.dayIndex == 6 ? 'success' : ''" :disabled="indexStore.loading"
          @click="changeTime(6)">上月</el-button>
        <el-tooltip effect="dark" placement="top" content="导出旗下商户数据账单">
          <el-button type="success" @click="data.isShowExport = true">导出账单</el-button>
        </el-tooltip>
        <el-button type="warning" @click="data.query.is_usdt_show = !data.query.is_usdt_show, getSearchList()">{{
          data.query.is_usdt_show ? '取消换算' :'换算USDT' }}</el-button>
        <div class="marginL10 flex">
          <p> <span v-show="data.query.is_usdt_show">【USDT】</span>{{ !indexStore.is_general_agent ? 'GGR' : '平台费用' }}汇总：<span 
            :class="colorClass(data.totalForm.share)">{{ data.totalForm.share }}</span> </p>
          <p> <span v-show="data.query.is_usdt_show">【USDT】</span> 总投注汇总：<span
            :class="colorClass(data.totalForm.total_bet)">{{ data.totalForm.total_bet }}</span> </p>
          <p> <span v-show="data.query.is_usdt_show">【USDT】</span> 总输赢汇总：<span
            :class="colorClass(data.totalForm.total_game_income)">{{ data.totalForm.total_game_income }}</span> </p>
          <p> <span v-show="data.query.is_usdt_show">【USDT】</span> {{ !indexStore.is_general_agent ? 'GGR返佣' : '平台费用返佣' }}汇总：<span
            :class="colorClass(data.totalForm.proportion)">{{ data.totalForm.proportion }}</span> </p>
        </div>
      </div>
    </template>
    <template #table>
      <template v-for="(item, index) in data.fields" :key="index">
        <el-table-column v-if="item.visible" :prop="item.prop" :label="item.label" :width="item.width"
          :sortable="item.sortable ? true : false" show-overflow-tooltip>
          <template #header>
            <el-tooltip v-if="item.tips" effect="dark" placement="top">
              <template #content>
                {{ item.tips }}
              </template>
              <el-icon class="ques-tips">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
            {{ item.label }}
          </template>
          <template v-if="item.prop == 'operated_id'" #default="scope">
            <div class="flex">
              <div class="marginR2" style="width: 55px;">
                <el-tag v-if="!indexStore.is_general_agent" size="small"
                  :type="selectToLabel(indexStore.operatorArray, scope.row.operated_id, 'currency', 'value') == 1 ? 'danger' : 'warning'"
                  style="font-size:10px;">
                  {{ selectToLabel(indexStore.operatorArray, scope.row.operated_id, 'currency', 'value') == 1 ? '多货币' :
                  '正常总代' }}
                </el-tag>
              </div>
              <span>{{ selectToLabel(indexStore.operatorArray, scope.row.operated_id) }}</span>
            </div>
          </template>
          <template v-if="item.prop == 'agent_id'" #default="scope">
            {{ selectToLabel(indexStore.agentArray, scope.row.agent_id) }}
          </template>
          <template v-if="item.prop == 'agent_area'" #default="scope">
            {{ selectToLabel(COUNTRY, scope.row.agent_area) }}
          </template>
          <template v-if="item.prop == 'total_bet'" #default="scope">
            <span class="colorText">{{ scope.row.total_bet }}</span>
          </template>
          <template v-if="item.prop == 'total_game_income'" #default="scope">
            <span class="details" :class="colorClass(scope.row.total_game_income)"
              @click="checkDetails(scope.row, 'slot_son')">
              {{ scope.row.total_game_income }}</span>
          </template>
          <template v-if="item.prop == 'ggrTotal'" #default="scope">
            <span :class="colorClass(scope.row.ggrTotal)">{{ scope.row.ggrTotal }}</span>
          </template>
          <template v-if="item.prop == 'config_ggr'" #default="scope">
            <span class="marginR5" v-for="(second, two) in scope.row.config_ggr">
              {{ selectToLabel(GameBrandNum, second.platform) }}:{{ second.radio }}%
            </span>
          </template>
          <template v-if="item.prop == 'share_proportion'" #default="scope">
            {{ scope.row.share_proportion ? scope.row.share_proportion + '%' : '-' }}
          </template>
          <template v-if="item.prop == 'ggrShare'" #default="scope">
            <span :class="colorClass(scope.row.ggrShare)">{{ scope.row.ggrShare }}</span>
          </template>
          <template v-if="item.prop == 'pre_score_status'" #default="scope">
            <span>{{ scope.row.pre_score_status ? scope.row.pre_store_score : '-' }}</span>
          </template>
        </el-table-column>
      </template>
    </template>
  </SearchTable>

  <!-- 变更表头弹框 -->
  <tableHeader :dialogVisible="data.dialogVisible" :list="data.fields" @cancel="data.dialogVisible = false"
    @resetData="resetData" />

  <!-- 导出 -->
  <PdfExport ref="PdfExportRef" :title="indexStore.BackOperator + '账单'" :show="data.isShowExport"
    @onHideDetails="onHideDetails" />

  <!-- 游戏详情 -->
  <el-dialog v-model="data.isShowDetails" width="60%" title="游戏详情" :close-on-click-modal="false" top="12vh"
    :close-on-press-escape="false" :destroy-on-close="true" @close="onHideDetails">
    <template #header>
      <p class="box-title mustPass">
        【{{ data.checkedItem.agent_id }}】 {{ selectToLabel(indexStore.agentArray, data.checkedItem.agent_id) }}
        <span style="color: #666666;">{{ data.checkedItem.currency }}</span>
      </p>
    </template>
    <div v-loading="indexStore.moduleLoading" class="dialogMaxHeight" style="overflow: hidden;">
      <el-tabs v-model="data.dataType" type="card" class="demo-tabs marginT5" @tab-click="handleClick">
        <el-tab-pane label="老虎机" name="slot_son" />
        <el-tab-pane label="百人场" name="hundred_son" />
        <el-tab-pane label="MiniGame" name="mine_son" />
      </el-tabs>
      <div class="statistic">
        <p v-show="data.dataType == 'slot_son'">
          老虎机流水: <span class="marginR30" :class="colorClass(data.checkedItem.slot_bet)">
            {{ BigWan(data.checkedItem.slot_bet) }}</span>
          老虎机输赢: <span :class="colorClass(data.checkedItem.slot_game_income)">
            {{ BigWan(data.checkedItem.slot_game_income) }}</span>
        </p>
        <p v-show="data.dataType == 'hundred_son'">
          百人场流水: <span class="marginR30" :class="colorClass(data.checkedItem.hundred_bet)">
            {{ BigWan(data.checkedItem.hundred_bet) }}</span>
          百人场输赢: <span :class="colorClass(data.checkedItem.hundred_game_income)">
            {{ BigWan(data.checkedItem.hundred_game_income) }}</span></p>
        <p v-show="data.dataType == 'mine_son'">
          Mine Game流水: <span class="marginR30" :class="colorClass(data.checkedItem.mine_bet)">
            {{ BigWan(data.checkedItem.mine_bet) }}</span>
          街机输赢: <span :class="colorClass(data.checkedItem.mine_game_income)">
            {{ BigWan(data.checkedItem.mine_game_income) }}</span></p>
      </div>
      <SearchTable v-loading="indexStore.moduleLoading" :list="data.listDetails" :total="data.totalDetails" :showForm="false" :showSet="false" @reset="onHideDetails(true)">
        <!-- <template #other>
          <el-tabs v-model="data.queryDetails.game_type" type="card" class="demo-tabs" @tab-change="handleClick">
            <el-tab-pane v-for="item in GAMETYPE" :label="item.label" :name="item.value" />
          </el-tabs>
        </template>
        <template #form>
          <GameItem ref="GameItemRef" @query="queryGame" :gameShow="false"/>
        </template>
        <template #button>
          <div class="statistic flex">
            <p>流水： <span class="colorText">{{ BigWan(data.totalFrom.total_bet) }}</span></p>
            <p>输赢：<span :class="colorClass(BigWan(data.totalFrom.game_income))">{{ BigWan(data.totalFrom.game_income) }}</span></p>
            <p>RTP：<span :class="colorClass(RtpPercent(data.totalFrom.total_win, data.totalFrom.total_bet))">{{ RtpPercent(data.totalFrom.total_win, data.totalFrom.total_bet) }}</span></p>
          </div>
        </template> -->
        <template #table>
          <template v-for="(item, index) in data.fieldDetails" :key="index">
            <el-table-column v-if="item.visible" :prop="item.prop" :label="item.label" :width="item.width" :sortable="item.sortable ? true : false">
              <template #header>
                <el-tooltip v-if="item.tips" effect="dark" placement="top">
                  <template #content>
                    {{ item.tips }}
                  </template>
                  <el-icon class="ques-tips">
                    <QuestionFilled />
                  </el-icon>
                </el-tooltip>
                {{ item.label }}
              </template>
              <template v-if="item.prop == 'game_id'" #default="scope">
                <GameHeaderInfo :game_id="scope.row.game_id" />
              </template>
              <template v-if="item.prop == 'game_bet'" #default="scope">
                <span class="colorText">{{ !indexStore.is_general_agent?BigWan(BigDiv(scope.row.game_bet,data.checkedItem.settlement_ratio)):BigWan(scope.row.game_bet) }}</span>
              </template>
              <template v-if="item.prop == 'game_income'" #default="scope">
                <span :class="colorClass(scope.row.game_income)">
                  {{ !indexStore.is_general_agent?BigWan(BigDiv(scope.row.game_income,data.checkedItem.settlement_ratio)):BigWan(scope.row.game_income) }}</span>
              </template>
              <template v-if="item.prop == 'radio'" #default="scope">
                {{ EarningPercent(scope.row.game_bet, scope.row.game_income) }}%
              </template>
            </el-table-column>
          </template>
        </template>
      </SearchTable>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onUpdated } from 'vue'
import tableHeader from '@/components/tableHeader/tableHeader.vue'
import SearchTable from '@/components/SearchTable/SearchTable.vue'
import PdfExport from '@/components/PdfExport.vue'
import GameHeaderInfo from '@/components/FormItem/GameHeaderInfo.vue'
import Operator, { type QueryType } from '@/components/FormItem/Operator.vue'
import { exportToExcel } from '@/utils/export'
import { throttle, selectToLabel, colorClass, CurrencyExchange, AgentCurrency, ArrayReduce } from '@/utils/index'
import { GameBrandNum } from '@/config/eunm'
import { COUNTRY } from '@/config/country'
import { getDateDay, getWeek, getMonth, setTimeValue } from '@/utils/time'
import { BigWan, BigHundred, BigDiv, BigTimes, EarningPercent, BigTofixedFour } from '@/utils/math'
import { getMerchantReportCurrency, getMerchantReport } from '@/api/instrument'

import { useStore } from '@/stores/index'
const indexStore = useStore()

const data = reactive({
  query: {
    page: 1,
    size: 50,
    agent_id: -1,
    currency_ids: [],
    area_s: [],
    operated_id: -1,
    currency_id: -1,
    is_usdt_show: false,
    date: [getDateDay(0), getDateDay(0)]
  },
  list: [],
  total: 0,
  dayIndex: 1,
  fields: [
    // Aviator属于百人，Mines属于街机，slot为老虎机
    { label: '日期', prop: 'date', width: '200', visible: true },
    { label: '上级渠道', prop: 'operated_id', width: '180', visible: true, tips: '商户的上级代理' },
    { label: '商户昵称', prop: 'agent_id', width: '120', visible: true, tips: '商户的名称' },
    { label: '地区', prop: 'agent_area', width: '100', visible: true, tips: '商户的经营区域，可更改，创建商户时的信息设定' },
    { label: '币种', prop: 'currency', width: '100', visible: true, tips: '商户游戏结算所使用的货币，不轻易更改，创建商户时的信息设定' },
    { label: !indexStore.is_general_agent ? 'GGR' : '平台费用', prop: 'ggrTotal', width: '150', visible: true, sortable: true, tips: '对应品牌的GGR*对应品牌商户的分成比例就是平台收入' },
    { label: '分成比例', prop: 'config_ggr', width: '120', visible: true, tips: '商户分成比例' },
    { label: '返佣分成', prop: 'share_proportion', width: '120', visible: !indexStore.is_general_agent, tips: '商户返佣分成比例' },
    { label: !indexStore.is_general_agent ? 'GGR返佣' : '平台费用返佣', prop: 'ggrShare', width: '150', visible: !indexStore.is_general_agent, sortable: true, tips: '总输赢*返佣分成' },
    { label: '总投注用户数', prop: 'total_valid_user', width: '150', visible: true, tips: '根据筛选日期内查询商户有下注过玩家数量' },
    { label: '总投注', prop: 'total_bet', width: '200', visible: true, sortable: true, tips: '根据筛选日期内查询商户的玩家下注额数量也称为玩家流水、注单额' },
    { label: '总输赢', prop: 'total_game_income', width: '200', visible: true, sortable: true, tips: '根据筛选日期内查询商户的输赢情况正为盈利、负为亏损' },
    // { label: '预存分', prop: 'pre_score_status', width: '120', visible: true, sortable: false, tips: '商户的输赢值达到预存分情况' },
  ],
  dialogVisible: false,
  isShowDetails: false,
  isShowExport: false,
  exportLoading: false,
  dataType: 'slot_son',
  checkedItem: {} as any,
  listDetails: [],
  totalDetails: 0,
  fieldDetails: [
    { label: '游戏名称', prop: 'game_id', width: '200', visible: true },
    { label: '总流水', prop: 'game_bet', width: '', visible: true, sortable: true, tips: '根据筛选日期内查询商户的玩家下注额数量也称为玩家流水、注单额' },
    { label: '总输赢', prop: 'game_income', width: '', visible: true, sortable: true, tips: '根据筛选日期内查询商户的输赢情况正为盈利、负为亏损' },
    { label: '投注用户数', prop: 'valid_user', width: '160', visible: true, sortable: true, tips: '今日进入游戏投注的人数，去重' },
    { label: '游戏次数', prop: 'game_count', width: '150', visible: true, sortable: true, tips: '今日进入此游戏的人数，去重' },
    { label: '游戏盈利率', prop: 'radio', width: '160', visible: true, sortable: true, tips: '投注 / 返奖  - 100%' }
  ],
  totalForm: {
    share: 0,
    total_bet: 0,
    total_game_income: 0,
    proportion: 0,
  },
  currentList: [] as any[]
})

// 商户类别 + 商户
const queryItem = (item: QueryType) => {
  data.query.agent_id = item.agent_id
  data.query.operated_id = item.operated_id
}

onMounted(async () => {
  data.query = indexStore.setQueryCache(data.query,'get')
  OperatorRef.value.setBackQuery(data.query)
  getCurrencyList()
  getSearchList()
})
onUpdated(() => {
  indexStore.setQueryCache(data.query,'set')
})


const getSearchList = async (type?: string) => {
  indexStore.setPageLoading(true)
  let query = JSON.parse(JSON.stringify(data.query));
  query.area_s = query.area_s.join(',')
  query.currency_ids = query.currency_ids.join(',')
  query = setTimeValue(query)
  
  if (type && type == 'export') {
    query.size = 10000
  }
  let res = await getMerchantReport(query), 
  shareArr = [] as number[],proportionArr = [] as number[], beteArr = [] as number[], incomeArr = [] as number[], exchange = 1;
  data.totalForm.share = 0
  data.totalForm.total_bet = 0
  data.totalForm.total_game_income = 0
  res.data.list?.forEach((item: any) => {
    item.date = data.query.date[0] + ' ~ ' + data.query.date[1]
    item.currency = AgentCurrency(item.agent_id)
    item.total_game_income = BigWan(item.total_game_income)
    item.total_bet = BigWan(item.total_bet)
    // 分成比例
    item.ggr = []
    if (item.platform_ggr && item.platform_radio) {
      item.config_ggr = [], item.ggrKey = Object.keys(item.platform_ggr), item.radioKey = Object.keys(item.platform_radio)
      item.ggrKey.forEach((key: number) => {
        item.ggr.push(BigWan(item.platform_ggr[Number(key)]))
      })
      item.radioKey.forEach((keys: number) => {
        item.config_ggr.push({ platform: Number(keys), radio: item.platform_radio[Number(keys)] })
      })
    }
    // GGR
    item.ggrTotal = BigTofixedFour(ArrayReduce(item.ggr))
    // GGR返佣 = 总输赢*返佣比例
    item.ggrShare = BigTimes(item.total_game_income, BigHundred(item.share_proportion))
    // 汇率换算
    if (data.query.is_usdt_show) {
      exchange = CurrencyExchange(item.agent_id)
      item.ggrTotal = BigTimes(item.ggrTotal, exchange)
      item.ggrShare = BigTimes(item.ggrShare, exchange)
      item.total_bet = BigTimes(item.total_bet,exchange)
      item.total_game_income = BigTimes(item.total_game_income,exchange)
      item.slot_son?.forEach((second:any) => {
        second.game_bet = BigTimes(second.game_bet,exchange)
        second.game_income = BigTimes(second.game_income,exchange)
      })
    }
    // 结算比列 
    if(!indexStore.is_general_agent){
      item.ggrTotal = BigDiv(item.ggrTotal,item.settlement_ratio)
      item.ggrShare = BigDiv(item.ggrShare,item.settlement_ratio)
      item.total_bet = BigDiv(item.total_bet,item.settlement_ratio)
      item.total_game_income = BigDiv(item.total_game_income,item.settlement_ratio)
      item.slot_bet = BigDiv(item.slot_bet,item.settlement_ratio)
      item.slot_game_income = BigDiv(item.slot_game_income,item.settlement_ratio)
      item.hundred_bet = BigDiv(item.hundred_bet,item.settlement_ratio)
      item.hundred_game_income = BigDiv(item.hundred_game_income,item.settlement_ratio)
      item.mine_bet = BigDiv(item.mine_bet,item.settlement_ratio)
      item.mine_game_income = BigDiv(item.mine_game_income,item.settlement_ratio)
    }
    item.ggrShare = item.ggrShare >= 0 ? item.ggrShare : 0
    // 汇总
    beteArr.push(item.total_bet)
    incomeArr.push(item.total_game_income)
    shareArr.push(item.ggrTotal)
    proportionArr.push(item.ggrShare)
  })
  // 导出
  if (type && type == 'export') {
    getExport(res.data.list)
    return
  }
  data.list = res.data.list
  data.total = res.data.total
  // 汇总
  data.totalForm.share = BigTofixedFour(ArrayReduce(shareArr))
  data.totalForm.total_bet = BigTofixedFour(ArrayReduce(beteArr))
  data.totalForm.total_game_income = BigTofixedFour(ArrayReduce(incomeArr))
  data.totalForm.proportion = BigTofixedFour(ArrayReduce(proportionArr))
}

// 商户使用货币
const getCurrencyList = async () => {
  let res = await getMerchantReportCurrency({});
  data.currentList = res.data
}


// 设置快捷查询时间
const changeTime = throttle((type: number) => {
  if (data.dayIndex == type) return false
  data.dayIndex = type
  switch (type) {
    case 1:
      data.query.date = [getDateDay(0), getDateDay(0)]
      break;
    case 2:
      data.query.date = [getDateDay(-1), getDateDay(-1)]
      break;
    case 3:
      data.query.date = getWeek(-1)
      break;
    case 4:
      data.query.date = getWeek(0)
      break;
    case 5:
      data.query.date = getMonth(0)
      break;
    case 6:
      data.query.date = getMonth(-1)
      break;
  }
  getSearchList()
}, 2000)

// 选择游戏tab
const handleClick = async (value: any) => {
  data.dataType = value.paneName
  checkDetails(data.checkedItem, data.dataType)
}
// 详情
const checkDetails = async (row: any, type: string) => {
  // indexStore.setModuleLoading(true)
  data.isShowDetails = true
  data.dataType = 'slot_son'
  data.checkedItem = row
  data.listDetails = row[type]
}

// 导出
const getExport = async (dataList: any) => {
  let header: string[] = []
  let list: never[][] = []

  data.fields.forEach((item) => {
    header.push(item.label)
  })

  dataList.forEach((item: { [x: string]: any }, index: any) => {
    let arr: never[] = []
    data.fields.forEach((x) => {
      switch (x.prop) {
        case 'date':
          arr.push(data.query.date[0] + ' ~ ' + data.query.date[1] as never)
          break
        case 'operated_id':
          arr.push(selectToLabel(indexStore.operatorArray, item[x.prop]) as never)
          break
        case 'agent_area':
          arr.push(selectToLabel(COUNTRY, item[x.prop]) as never)
          break
        case 'agent_id':
          arr.push(selectToLabel(indexStore.agentArray, item[x.prop]) as never)
          break
        case 'currency':
          arr.push(AgentCurrency(item['agent_id']) as never)
          break
        case 'config_ggr':
          let name = ''
          item[x.prop].forEach((second: any) => {
            name += selectToLabel(GameBrandNum, second.platform) + ':' + second.radio + '% '
          })
          arr.push(name as never)
          break
        case 'share_proportion':
          arr.push(item[x.prop] + '%' as never)
          break
        case 'share':
          arr.push(item['ggrTotal'] as never)
          break
        // case 'pre_score_status':
        //   arr.push((item[x.prop] ? item['pre_store_score'] : '-') as never)
        //   break
        default:
          arr.push(item[x.prop] as never)
          break
      }
    })
    list.push(arr)
  })
  exportToExcel(list, header, '商户报表')
}

// 修改页数
const changeSize = (val: number) => {
  data.query.size = val
}

const changePage = (val: number) => {
  data.query.page = val
  getSearchList()
}

// 重置表头
const resetData = (val: any) => {
  data.fields = val
}

// 重置
const OperatorRef = ref<any>()
const onHideDetails = (show: boolean) => {
  data.isShowExport = false
  if (show) {
    data.query = {
      page: 1,
      size: 50,
      currency_ids: [],
      area_s: [],
      agent_id: -1,
      operated_id: -1,
      currency_id: -1,
      is_usdt_show: false,
      date: [getDateDay(0), getDateDay(0)]
    }
    OperatorRef.value.onHideDetails()
    getSearchList()
  }
}
</script>

<style scoped lang="scss">
.formItem500 {
  width: 500px;
}
</style>